package com.ddyang.Webflux.handler;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

@Component
public class MyWebHandler {

    /**
     * @param serverRequest :
     * @author : daniel.yang
     * @date : 2019/3/11
     * @desc : 获取时间的一般方式
     */
    public Mono<ServerResponse> getDate(ServerRequest serverRequest) {
        return ok()
                       .contentType(MediaType.TEXT_PLAIN)
                       .body(Mono.just("Today is " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())), String.class);
    }

    /**
     * @param serverRequest :
     * @author : daniel.yang
     * @date : 2019/3/11
     * @desc : 服务器推送 流式推送时间到客户端
     */
    public Mono<ServerResponse> sendTimePerSec(ServerRequest serverRequest) {
        return ok()
                       .contentType(MediaType.TEXT_EVENT_STREAM).body(  // 1 text/event-stream 表明服务端发送的是流数据
                        Flux.interval(Duration.ofSeconds(1))   // 2
                        .map(l -> new SimpleDateFormat("HH:mm:ss").format(new Date())),
                        String.class);
    }
}
